package com.starblink.android.basic.util

import kotlinx.coroutines.*

class CoroutineUpdateTask {
    private var scope: CoroutineScope? = null

    fun scheduleUpdate(interval: Long,action:()->Unit) {
        cancel()
        val scope = CoroutineScope(Dispatchers.IO)
        scope.launch {
            while (isActive) {
                try {
                    action.invoke()
                } catch (e: Exception) {
                    e.printStackTrace()
//                    if (e is CancellationException) throw e
                }
                delay(interval)
            }
        }

        this.scope = scope
    }

    fun cancel() {
        scope?.cancel()
        scope = null
    }


}